package com.cloudeye.monitor.listener;

import com.cloudeye.monitor.service.AppInfoService;
import com.cloudeye.monitor.service.CacheService;
import org.I0Itec.zkclient.ZkClient;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description: ClassDescription
 * @Author: Zengzhihong
 * @Date: Create at 2018/3/13 15:05
 */
public class AppStatusChangeListener implements PathChildrenCacheListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(AppStatusChangeListener.class);
    private ZkClient zkClient;
    private AppInfoService appInfoService;

    public AppStatusChangeListener(ZkClient zkClient,AppInfoService appInfoService) {
        this.zkClient = zkClient;
        this.appInfoService = appInfoService;
    }
    @Override
    public void childEvent(CuratorFramework curator, PathChildrenCacheEvent event) throws Exception {
        LOGGER.info("event.type="+event.getType());
        switch (event.getType()){
            case CHILD_ADDED:
                PathChildrenCache pathChildrenCache = new PathChildrenCache(curator, event.getData().getPath(), true);
                pathChildrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
                //对上线应用进行监控
                pathChildrenCache.getListenable().addListener(new AppStatusChildrenChangeListener(this.zkClient,this.appInfoService));
                LOGGER.info("app added: " + event.getData().getPath());
                break;
            case CHILD_REMOVED:
                LOGGER.info("app removed: " + event.getData().getPath());
                break;
            default:;
        }
    }
}
